import { useState, useEffect } from 'react';
import echarts from 'echarts'
import './index.less';

const StiffWoodCategory = ({ dataValue }) => {
  const [categoryData, setCategoryData] = useState({})
  const [arrCategoryData, SetArrCategoryData] = useState([])
  //categoryData: {},
  // arrCategoryData: []
  console.log('--------------------------', dataValue)
  //
  useEffect(() => {

    setCategoryData({"僵尸网络": 153,
      "其它": 6241,
      "木马": 6808,
      "病毒": 1383,
      "蠕虫": 493})
  }, [])

  useEffect(() => {
    setOption()
    console.log('我是setOption()-----渲染后的数据', categoryData)
  }, [categoryData])


  const setOption = () => {
    let myChart = echarts.init(document.getElementById('sti-ffWoodCategory-chart'));
    let legendData = [],
        data = [],
        label = [];

    for (let i in categoryData) {
        // arrCategoryData.push({
        //   name: i,
        //   value: categoryData[i]
        // })
        // 数据更新方式改变
        SetArrCategoryData([...arrCategoryData, {
          name: i,
          value: categoryData[i]}]
          )
        legendData.push({
          name: i,
          icon: 'circle'
        })
        data.push(categoryData[i])
        label.push(i)
    }

    let option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 15,
        top: 'middle',
        data: legendData,
        textStyle: {
          color: '#fff'
        },
        itemWidth: 10,
        itemHeight: 10,
        formatter: function(name) {
          let sum = 0,
              index = 0;
          data.map(d => {
            sum += d;
          })
          label.forEach((value, i) => {
            if (value == name) {
                index = i;
            }
          })
         return name + ' - ' + (data[index] / sum * 100).toFixed(2) + '%'
        }
      },
      series: [
        {
          name: '僵木蠕毒类型分布',
          type: 'pie',
          radius: ['32%', '62%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: false,
          label: {
            normal: {
              show: false
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          data: arrCategoryData
        }
      ],
      color: ['#00E1D6', '#00918A', '#FF528A', '#FFCB81', '#148BFF']
    }
    console.log('option:', option)
    myChart.setOption(option)
    myChart.resize()
  }

  return (
    <div className="sti-ffWoodCategory-container">
      <div className="sti-ffWoodCategory-chart" id="sti-ffWoodCategory-chart" ></div>
    </div>
  )
}

export default StiffWoodCategory;
